<?php
namespace App\Http\Controllers\Api\v1;

use App\Comment as CommentModel;
use App\Http\Controllers\Api\BaseController;
use App\Http\Resources\Comment;
use App\Http\Resources\CommentCollection;
use App\Repositories\CommentRepository;
use App\Scopes\StatusScope;
use App\Traits\BaseApiFunc;
use Auth;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CommentController extends BaseController {

	use BaseApiFunc;

	protected $model, $page_size;

	public function __construct(CommentRepository $comment) {
		parent::__construct();

		$this->model = $comment;
		$this->page_size = config('blog.admin_page.common_page');
	}

	public function reply(Request $request) {
		$this->validate($request, [
			'item_id' => 'required|numeric',
			'content' => 'required',
		]);
		$user = [
			'id' => Auth::user()->id,
			'avatar' => Auth::user()->avatar,
			'name' => Auth::user()->name,
		];
		$list = $this->model->store(array_merge(['user_id' => $user['id']], $request->all()));
		return $this->response->withSuccess(array_merge($list, compact('user')));
	}

	public function randReply() {
		$list = Cache::remember('randReply', 30, function () {
			return (new CommentCollection($this->model->getRandReply()->load(['user'])))->type('index');
		});
		return $list;
	}

	protected function getResourceCollection(Collection $collection) {
		return new CommentCollection($collection->load(['user' => function ($query) {
			return $query->withoutGlobalScope(StatusScope::class);
		}])->load(['item' => function ($query) {
			return $query->withoutGlobalScope(StatusScope::class);
		}]));
	}

	protected function getResource(CommentModel $collection) {
		return new Comment($collection);
	}
}
